/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package construtora.limiar.servlet;

import construtora.limiar.dao.InsumoDAO;
import construtora.limiar.models.Insumo;
import construtora.limiar.util.Utilidades;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Date;
import java.util.List;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 *
 * @author michel
 */
@WebServlet(name = "InsumoSlt", urlPatterns = {"/InsumoSlt"})
public class InsumoSlt extends AuthSlt {

    /**
     * Processes requests for both HTTP
     * <code>GET</code> and
     * <code>POST</code> methods.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        operacao = request.getParameter("operacao");
        chave = request.getParameter("chave");
        String novo = request.getParameter("novo");
        RequestDispatcher rd = null;

        String[] TIPOS = new String[]{"Básico", "Acabamento", "Hidraúlico", "Elétrico"};
        /*
         Usuario usuario = (Usuario) getServletContext().getAttribute("usuario");
         AuthorizationController ac = AuthorizationController.getInstance(usuario.getApelido());
        
         if (!ac.hasRole(new String[]{Papeis.GRAVADOR,Papeis.ADMINISTRADOR})){
         Message.setLastInfo("Você não tem permissão para usar este recurso!");
         response.sendRedirect("admin.jsp");
         return;
         }
        
         String cadastro = request.getParameter("cadastro");
         String retornar = request.getParameter("retornar");
         if (retornar != null) {
         response.sendRedirect("cadastro.jsp?cadastro=" + cadastro);
         return;
         }
         */
        //if (request.getCharacterEncoding() == null)
        request.setCharacterEncoding("UTF-8");
        response.setCharacterEncoding("text/html;charset=UTF8");

        if ("incluir".equals(operacao)) {
            try {
                request.setAttribute("TIPOS", TIPOS);
                rd = request.getRequestDispatcher("/gravarInsumo.jsp");
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        if ("gravar".equals(operacao) || "novo".equals(operacao)) {
            Insumo insumo = new Insumo();
            InsumoDAO dao = new InsumoDAO();
            insumo.setDescricao(request.getParameter("descricao"));
            insumo.setFabricante(request.getParameter("fabricante"));
            insumo.setTipo(request.getParameter("tipo"));
            insumo.setPeso(Double.parseDouble(request.getParameter("peso")));
            insumo.setCor(request.getParameter("cor"));
            insumo.setUnidade(request.getParameter("unidade"));
            Date data_de_validade = Utilidades.trataData(request.getParameter("data_de_validade"));
            insumo.setDataValidade(data_de_validade);
            insumo.setQuantidade(Integer.parseInt(request.getParameter("quantidade")));
            insumo.setQuantidadeMinima(Integer.parseInt(request.getParameter("quantidade_minima")));
            insumo.setStatus(request.getParameter("status"));
            if (insumo.getId() == null) {
                dao.insert(insumo);
                insumo.setId(dao.getLast(insumo));
            } else {
                dao.update(insumo);
            }
            if ("novo".equals(operacao)) {
                rd = request.getRequestDispatcher("InsumoSlt?operacao=incluir");
            } else {
                rd = request.getRequestDispatcher("InsumoSlt?operacao=listar");
            }
        }
        if ("listar".equals(operacao)) {
            try {
                InsumoDAO dao = new InsumoDAO();                
                List insumos = dao.fetchAll("status = 'ativo'", null, null, null);                
                request.setAttribute("insumos", insumos);                
                rd = request.getRequestDispatcher("/listarInsumo.jsp");
            } catch (Exception e) {
                e.printStackTrace();
            }
        }



        if (rd != null) {
            rd.forward(request, response);
        }

    }

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /**
     * Handles the HTTP
     * <code>GET</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /**
     * Handles the HTTP
     * <code>POST</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /**
     * Returns a short description of the servlet.
     *
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>
}
